<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋在线对战 - 游戏对战</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <div class="game-info-bar fade-in">
            <div class="player-info">
                <span class="player-name">玩家001</span>
                <span class="player-score">积分: 126</span>
            </div>
            
            <div class="turn-indicator" id="turn-indicator">
                轮到黑方落子
            </div>
            
            <div class="player-info">
                <span class="player-name">玩家002</span>
                <span class="player-score">积分: 118</span>
            </div>
        </div>
        
        <div class="game-container fade-in">
            <!-- 棋盘区域 -->
            <div class="board-container">
                <div class="game-board" id="game-board">
                    <!-- 棋盘将由JavaScript动态生成 -->
                </div>
            </div>
            
            <!-- 游戏控制面板 -->
            <div class="game-controls">
                <div class="game-status" id="game-status">
                    游戏进行中
                </div>
                
                <div class="game-timer" id="game-timer">
                    思考时间: 30秒
                </div>
                
                <button id="surrender-btn" class="btn btn-danger" style="width: 100%; margin-bottom: 15px;">认输</button>
                <button id="return-btn" class="btn btn-primary" style="width: 100%; display: none;">返回大厅</button>
                
                <div id="game-result" style="display: none;">
                    <div class="game-result" id="result-text"></div>
                    <div class="score-change" id="score-change"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 游戏状态变量
        let gameActive = true;
        let currentPlayer = 'black'; // 'black' 或 'white'
        let board = Array(15).fill().map(() => Array(15).fill(null));
        let lastMove = null;
        let timer = 30;
        let timerInterval;
        
        // DOM元素
        const gameBoard = document.getElementById('game-board');
        const turnIndicator = document.getElementById('turn-indicator');
        const gameStatus = document.getElementById('game-status');
        const gameTimer = document.getElementById('game-timer');
        const surrenderBtn = document.getElementById('surrender-btn');
        const returnBtn = document.getElementById('return-btn');
        const gameResult = document.getElementById('game-result');
        const resultText = document.getElementById('result-text');
        const scoreChange = document.getElementById('score-change');
        
        // 初始化棋盘
        function initBoard() {
            gameBoard.innerHTML = '';
            
            for (let i = 0; i < 15; i++) {
                for (let j = 0; j < 15; j++) {
                    const cell = document.createElement('div');
                    cell.classList.add('board-cell');
                    cell.dataset.row = i;
                    cell.dataset.col = j;
                    
                    cell.addEventListener('click', () => handleCellClick(i, j));
                    
                    gameBoard.appendChild(cell);
                }
            }
            
            // 开始计时器
            startTimer();
        }
        
        // 处理单元格点击
        function handleCellClick(row, col) {
            // 如果游戏已结束或该位置已有棋子，则不处理
            if (!gameActive || board[row][col] !== null) {
                return;
            }
            
            // 放置棋子
            placePiece(row, col, currentPlayer);
            
            // 检查是否获胜
            if (checkWin(row, col, currentPlayer)) {
                endGame(true);
                return;
            }
            
            // 切换玩家
            currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
            turnIndicator.textContent = `轮到${currentPlayer === 'black' ? '黑' : '白'}方落子`;
            
            // 重置计时器
            resetTimer();
            
            // 模拟对手落子（白方）
            if (currentPlayer === 'white') {
                setTimeout(() => {
                    // 简单AI：随机找一个空位置
                    let emptyCells = [];
                    for (let i = 0; i < 15; i++) {
                        for (let j = 0; j < 15; j++) {
                            if (board[i][j] === null) {
                                emptyCells.push({row: i, col: j});
                            }
                        }
                    }
                    
                    if (emptyCells.length > 0) {
                        const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
                        handleCellClick(randomCell.row, randomCell.col);
                    }
                }, 1000);
            }
        }
        
        // 放置棋子
        function placePiece(row, col, player) {
            board[row][col] = player;
            
            // 移除上一步的标记
            if (lastMove) {
                const lastCell = gameBoard.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
                const lastPiece = lastCell.querySelector('.piece');
                if (lastPiece) {
                    lastPiece.classList.remove('last-move');
                }
            }
            
            // 创建棋子元素
            const cell = gameBoard.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const piece = document.createElement('div');
            piece.classList.add('piece', player, 'last-move', 'bounce');
            cell.appendChild(piece);
            
            // 记录最后一步
            lastMove = {row, col};
        }
        
        // 检查是否获胜
        function checkWin(row, col, player) {
            const directions = [
                {dr: 1, dc: 0},  // 垂直
                {dr: 0, dc: 1},  // 水平
                {dr: 1, dc: 1},  // 对角线 /
                {dr: 1, dc: -1}   // 对角线 \
            ];
            
            for (const dir of directions) {
                let count = 1;  // 当前位置已经有一个棋子
                
                // 正向检查
                for (let i = 1; i <= 4; i++) {
                    const r = row + dir.dr * i;
                    const c = col + dir.dc * i;
                    
                    if (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] === player) {
                        count++;
                    } else {
                        break;
                    }
                }
                
                // 反向检查
                for (let i = 1; i <= 4; i++) {
                    const r = row - dir.dr * i;
                    const c = col - dir.dc * i;
                    
                    if (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] === player) {
                        count++;
                    } else {
                        break;
                    }
                }
                
                // 如果连成五子，则获胜
                if (count >= 5) {
                    return true;
                }
            }
            
            return false;
        }
        
        // 结束游戏
        function endGame(isWin) {
            gameActive = false;
            clearInterval(timerInterval);
            
            gameStatus.textContent = '游戏结束';
            surrenderBtn.style.display = 'none';
            returnBtn.style.display = 'block';
            gameResult.style.display = 'block';
            
            if (isWin) {
                if (currentPlayer === 'black') {
                    resultText.textContent = '你赢了！';
                    resultText.classList.add('result-win');
                    scoreChange.textContent = '+5分';
                    scoreChange.style.color = '#2ECC71';
                } else {
                    resultText.textContent = '你输了！';
                    resultText.classList.add('result-lose');
                    scoreChange.textContent = '-3分';
                    scoreChange.style.color = '#E74C3C';
                }
            } else {
                // 认输
                resultText.textContent = '你认输了！';
                resultText.classList.add('result-lose');
                scoreChange.textContent = '-3分';
                scoreChange.style.color = '#E74C3C';
            }
        }
        
        // 开始计时器
        function startTimer() {
            timerInterval = setInterval(() => {
                timer--;
                gameTimer.textContent = `思考时间: ${timer}秒`;
                
                if (timer <= 0) {
                    // 时间到，当前玩家输
                    clearInterval(timerInterval);
                    if (currentPlayer === 'black') {
                        endGame(false);
                    } else {
                        endGame(true);
                    }
                }
            }, 1000);
        }
        
        // 重置计时器
        function resetTimer() {
            clearInterval(timerInterval);
            timer = 30;
            gameTimer.textContent = `思考时间: ${timer}秒`;
            startTimer();
        }
        
        // 认输按钮事件
        surrenderBtn.addEventListener('click', () => {
            if (confirm('确定要认输吗？')) {
                endGame(false);
            }
        });
        
        // 返回大厅按钮事件
        returnBtn.addEventListener('click', () => {
            window.location.href = 'hall.html';
        });
        
        // 初始化游戏
        initBoard();
    </script>
</body>
</html>
